package cn.com.chengmandian.bike.service.impl;

import cn.com.chengmandian.agent.utils.AuthUtil;
import cn.com.chengmandian.bike.dto.FaultReportDto;
import cn.com.chengmandian.bike.dto.FaultReportForm;
import cn.com.chengmandian.bike.mapper.EbFaultReportMapper;
import cn.com.chengmandian.bike.model.EbDeviceBike;
import cn.com.chengmandian.bike.model.EbFaultReport;
import cn.com.chengmandian.bike.model.vo.FaultReportVo;
import cn.com.chengmandian.bike.service.IEbDeviceBikeService;
import cn.com.chengmandian.bike.service.IEbFaultReportService;
import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.com.chengmandian.core.common.utils.BillNoUtil;
import cn.com.chengmandian.service.bike.IotBikeClient;
import cn.com.chengmandian.service.bike.constants.BikeStatusEnum;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 故障上报 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2021-12-16
 */
@Slf4j
@Service
public class EbFaultReportServiceImpl extends ServiceImpl<EbFaultReportMapper, EbFaultReport> implements IEbFaultReportService {

    @Autowired
    private IEbDeviceBikeService deviceBikeService;

    @Autowired
    private IotBikeClient iotBikeClient;

    @Override
    public IPage<FaultReportVo> getPage(FaultReportDto vo) {
        Page page = Page.of(vo.getPageNumber(), vo.getPageSize());
        return baseMapper.getPage(page, vo);
    }

    @Override
    public void addData(FaultReportForm faultReportForm){
        EbDeviceBike deviceBike = deviceBikeService.getByNo(faultReportForm.getBikeNo());
        Assert.isTrue(deviceBike.getStatus().equals(BikeStatusEnum.USE_STATUS.getCode()) || deviceBike.getStatus().equals(BikeStatusEnum.WAIT_DISPATCH_STATUS.getCode()), "抱歉，当前车辆不在运营中");

        EbFaultReport ebFaultReport = new EbFaultReport();
        BeanUtils.copyProperties(faultReportForm,ebFaultReport);
        //故障单号
        ebFaultReport.setReportNo(BillNoUtil.getSimpleNo("FR-"));
        //用户id
        ebFaultReport.setMemberId(faultReportForm.getMemberId());
        //通过车辆编号获取车辆信息
        ebFaultReport.setBikeId(deviceBike.getId());
        //上报状态
        ebFaultReport.setReportStatus(0);
        this.save(ebFaultReport);

        this.updateBikeFault(deviceBike.getId());
        try {
            // 强制更新车辆标记
            iotBikeClient.updateBikeSysTags(deviceBike.getId());
        } catch (Exception e) {
            log.error("iotBikeClient.updateBikeSysTags error!", e);
        }
    }

    private void updateBikeFault(Integer bikeId) {
        List<EbFaultReport> reportList = this.list(new LambdaQueryWrapper<EbFaultReport>().eq(EbFaultReport::getBikeId, bikeId).in(EbFaultReport::getReportStatus, CommonConstant.ZERO, CommonConstant.ONE));
        Set<String> res = new HashSet<>();
        reportList.stream().forEach(i -> {
            if (StrUtil.isNotBlank(i.getFaultType())) {
                String[] arr = i.getFaultType().split(",");
                for (String item : arr) {
                    if (StrUtil.isNotEmpty(item)) {
                        res.add(item);
                    }
                }
            }
        });

        List<Integer> source = new ArrayList<>();
        reportList.stream().forEach(i -> {
            if (!source.contains(i.getSource())) {
                source.add(i.getSource());
            }
        });

        deviceBikeService.update(new LambdaUpdateWrapper<EbDeviceBike>()
                .set(EbDeviceBike::getFaultReport,  "," +  ArrayUtil.join(res.toArray(), ",", "", "") + ",")
                .set(EbDeviceBike::getFaultSource,ArrayUtil.join(source.toArray(),",","",""))
                .eq(EbDeviceBike::getId, bikeId));
    }

    @Override
    public FaultReportVo detailData(Integer id){
        return baseMapper.detailData(id);
    }

    @Override
    public void cancelApply(Integer id){
        EbFaultReport faultReport = this.getById(id);
        Assert.notNull(faultReport, "信息不存在");
        Assert.isTrue(faultReport.getMemberId().equals(AuthUtil.getAgentUser().getId()), "信息不存在");
        Assert.isTrue(faultReport.getReportStatus().equals(CommonConstant.ZERO), "当前无法撤销");

        this.update(new LambdaUpdateWrapper<EbFaultReport>().set(EbFaultReport::getReportStatus,CommonConstant.THREE).eq(EbFaultReport::getId, id));

        this.updateBikeFault(faultReport.getBikeId());
    }

    @Override
    public void deleteCancelApply(Integer id){
        EbFaultReport faultReport = this.getById(id);
        Assert.notNull(faultReport, "信息不存在");
        Assert.isTrue(faultReport.getMemberId().equals(AuthUtil.getAgentUser().getId()), "信息不存在");
        Assert.isTrue(faultReport.getReportStatus().equals(CommonConstant.THREE), "当前无法移除");

        this.remove(new LambdaQueryWrapper<EbFaultReport>().eq(EbFaultReport::getId, id));
    }
}
